package com.pf.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/6/27 21:57
 */
@Configuration
public class ExecutorConfig {

    @Value("${common.thread.core.pool.size:2}")
    private int corePoolSize;
    @Value("${common.thread.max.pool.size:6}")
    private int maximumPoolSize;
    @Value("${common.thread.keep.alive.time:30}")
    private long keepAliveTime;


    @Bean
    public ThreadPoolExecutor createThreadPoolExecutor() {
        return new ThreadPoolExecutor(
                // 核心线程数，线程池中始终存活的线程数
                corePoolSize,
                // 最大线程数，线程池中允许的最大线程数
                maximumPoolSize,
                // 存活时间，线程没有任务运行时最多保持多久时间会终止
                keepAliveTime,
                // 参数keepAliveTime的时间单位
                TimeUnit.SECONDS,
                // 一个由数组结构组成的有界阻塞队列，用于存储等待执行的任务，均为线程安全
                new ArrayBlockingQueue<>(3),
                // 线程工厂，主要用来创建线程
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, ">>>>>threadPoolExecutor-" + r.hashCode());
                    }
                },
                // 拒绝策略：拒绝并抛出异常
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
}
